package com.xuecheng.basic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.basic.domain.Category;
import com.xuecheng.basic.mappers.CategoryMapper;
import com.xuecheng.basic.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.commons.model.vo.CategoryVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.BeanHelper;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 课程分类 服务实现类
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    //查询课程分类信息
    public ResponseResult<CategoryVo> findTreeNodes() {
        //1、查询1级课程分类：根据parentid查询，查询数据=0
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper();
        qw.eq(Category::getParentid,"0");
        Category one = this.getOne(qw);
        CategoryVo vo = BeanHelper.copyProperties(one, CategoryVo.class);  //一级
        //2、查询2级课程分类：根据parentId查询，查询数据1级课程id
        List<CategoryVo> twos = this.findByParentId(one.getId());
        vo.setCategoryTreeNodes(twos);
        //3、循环所有的2级课程
        for (CategoryVo two : twos) {
            //4、查询每个2级课程包含的三级分类：根据parentId查询，查询数据2级课程id
            List<CategoryVo> threes = findByParentId(two.getId());
            two.setCategoryTreeNodes(threes);
        }

        //5、返回
        return ResponseResult.okResult(vo);
    }

    public List<CategoryVo> findByParentId(String parentId) {
        LambdaQueryWrapper<Category> qww = new LambdaQueryWrapper();
        qww.eq(Category::getParentid,parentId);
        List<Category> list = this.list(qww);
        List<CategoryVo> vos = BeanHelper.copyWithCollection(list, CategoryVo.class);
        return vos;
    }
}
